package com.farmer.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.farmer.pojo.User;
import com.farmer.service.UserService;
import com.farmer.mapper.UserMapper;
import com.farmer.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 86183
* @description 针对表【user(用户信息表)】的数据库操作Service实现
* @createDate 2024-04-18 09:30:26
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public Result add(User user) {
        return Result.ok(null);
    }

/*
* 用户封禁*/
@Override public Result deleteUser(Integer id) {
    // 检查用户是否存在
    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.eq(User::getId, id);
    Long count = userMapper.selectCount(lambdaQueryWrapper);
    if (count == 0) {
        return Result.build(null, ResultCodeEnum.USER_NOTEXSIST);
    }
    User user = userMapper.selectById(id);
    if (user.getStatus().equals(0)){
    user.setStatus(1);
    int affactedRows = userMapper.updateById(user);
    if (affactedRows>0){
        return Result.ok(null);
    }else{
      return Result.build(null,ResultCodeEnum.FAULT);
    }
    }
    else return Result.build(null,303,"用户已处于封禁状态");

}

    /*
     * 用户解封*/
    @Override
    public Result deblock(Integer id) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getId,id);
        Long count = userMapper.selectCount(lambdaQueryWrapper);
        if(count==0){
            return  Result.build(null,ResultCodeEnum.USER_NOTEXSIST);
        }
        User user = userMapper.selectById(id);
        if (user.getStatus().equals(1)){
            user.setStatus(0);
            int affactedRows = userMapper.updateById(user);
            if (affactedRows>0){
                return Result.ok(null);
            }else{
                return  Result.build(null,ResultCodeEnum.FAULT);
            }
        }else return Result.build(null,304,"用户已处于解封状态");

    }

    @Override
    public Result update(User user) {
        userMapper.updateById(user);
        return Result.ok(null);
    }


    @Override
    public Result getById(Integer id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            return Result.build(user, 111, "查询成功");
        } else {
            return Result.build(null, 101, "查询失败");
        }
    }

    @Override
    public Result getAll() {
        List<User> users = userMapper.selectList(null);
        if (users != null && !users.isEmpty()) {
            return Result.build(users, 111, "查询成功");
        } else {
            return Result.build(null, 101, "查询失败");
        }
    }

    /*
    * 根据标题模糊查询*/
    @Override
    public Result getByTitleLike(String name){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(User::getUsername,name);
        List<User> users = userMapper.selectList(lambdaQueryWrapper);
        if (users!=null&&!users.isEmpty()){
            return Result.build(users,111,"查询成功");
        }else{
            return Result.build(null,101,"未找到匹配信息");
        }
    }


    /*
     * 登录业务
     * 1.根据账号，查询用户对象
     * 2.如果用户对象为空，查询失败，账号错误-501
     * 3.对比密码，失败返回503状态码
     * 4.跟据用户id生成一个token，token->result 返回
     * */
    @Override
    public Result login(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        User loginUser = userMapper.selectOne(lambdaQueryWrapper);
        if (loginUser == null) {
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        if (loginUser.getStatus().equals(0)) {
            //对比密码
            if (!StringUtils.isEmpty(user.getPassword())
                    && MD5Util.encrypt(user.getPassword()).equals(loginUser.getPassword())) {
                    //登陆成功
                    //跟据用户id生成token
                    String token = jwtHelper.createToken(Long.valueOf(loginUser.getId()));
                    // 并将token封装result返回
                    Map data = new HashMap();
                    data.put("token", token);
                    data.put("user",loginUser);
                    return Result.ok(data);
            }
            //密码错误
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        } else return Result.build(null,900,"用户被封禁");

    }
   /*
   根据token获取用户数据
   * 1.token是否在有效期
   2.根据token解析userid
   3.根据用户id查询用数据
   4.去掉密码，封装result结果返回
   * */

    @Override
    public Result getUserInfo(String token) {
        boolean expiration = jwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.NOTLOGIN);
        }
        int userId = jwtHelper.getUserId(token).intValue();
        User user = userMapper.selectById(userId);
        if (user != null) {
            user.setPassword(null);
            Map data = new HashMap();
            data.put("loginUser", user);
            return Result.ok(data);
        }
        return Result.build(null, ResultCodeEnum.NOTLOGIN);

    }

    /*
     * 检查账号是否可用
     * 1.根据账号进行count查询
     * 2.count==0 可用
     * 3.count>0  不可用
     * */
    @Override
    public Result checkUserName(String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        Long count = userMapper.selectCount(lambdaQueryWrapper);
        if (count == 0) {
            return Result.ok(null);
        }
        return Result.build(null, ResultCodeEnum.USERNAME_USED);
    }
    /*
     * 注册业务
     * 1.依然检查账号是否被注册
     * 2.密码加密处理
     * 3.账号数据保存
     * 4.返回结果
     * */

    @Override
    public Result register(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        Long count = userMapper.selectCount(lambdaQueryWrapper);
        if (count > 0) {
            return Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        user.setPassword(MD5Util.encrypt(user.getPassword()));
        user.setLevel("普通户");
        user.setRole("USER");
        user.setStatus(0);
        user.setEmail("");
        user.setPhone("");
        user.setName("");
        userMapper.insert(user);
        return Result.ok(null);
    }

    @Override
    public Result updatePassword(String token, String newPassword) {
        int id = jwtHelper.getUserId(token).intValue();
        User loginUser = userMapper.selectById(id);
        if (loginUser == null) {
            return Result.build(null, 600, "用户不存在");
        }
        String encryptedNewPassword = MD5Util.encrypt(newPassword);
        String password = loginUser.getPassword();
        if (password.equals(encryptedNewPassword)) {
            return Result.build(null, 600, "新密码不能与旧密码相同");
        }
        loginUser.setPassword(encryptedNewPassword);
        userMapper.updateById(loginUser);
        return Result.ok(null);
    }


    @Override
    public Result avatarInsert(Integer id, MultipartFile file, String username, String name, String phone, String email, String level) {
        try {
            String url = Upload.uploadImage(file);
            System.out.println("图片的url：" + url);
            // 首先检查ID是否已存在于数据库中
            User user = userMapper.selectById(id);
            if (user == null) {
                // ID不存在，添加新记录
                User newUser = new User();
                newUser.setId(id);
               newUser.setAvatar(url);
               newUser.setUsername(username);
               newUser.setName(name);
               newUser.setPhone(phone);
               newUser.setEmail(email);
               newUser.setLevel(level);
                userMapper.insert(newUser);
                return Result.build(url, ResultCodeEnum.SUCCESS);
            } else {
                // ID存在，更新现有记录的图片URL
                user.setAvatar(url);
                userMapper.updateById(user);
                return Result.build(url, ResultCodeEnum.SUCCESS);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.build(null, ResultCodeEnum.FAULT);
        }
    }



  @Override
    public Result getAvatar(Integer id){
////      得到用户id
//      int id = jwtHelper.getUserId(token).intValue();
//      获取登录对象
      User user = userMapper.selectById(id);
      System.out.println(user.getAvatar());
      return Result.ok(user.getAvatar());
  }
    /*
     * 分页查询*/
    @Override
    public Result page(Integer pageNum, Integer pageSize){
        // 创建分页构造对象
        Page<User> page = new Page<>(pageNum, pageSize);
        // 执行分页查询
        IPage<User> result = userMapper.selectPage(page, null);
        // 封装到统一响应体Result中
        return Result.ok(result);
    }

}



